<?php

namespace app\admin\model;

use think\Model;
use traits\model\SoftDelete;

class Questions extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'questions';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'typedata_text',
        'diffdata_text'
    ];
    

    
    public function getTypedataList()
    {
        return ['1' => __('Typedata 1'), '2' => __('Typedata 2'), '3' => __('Typedata 3'), '4' => __('Typedata 4'), '5' => __('Typedata 5')];
    }

    public function getDiffdataList()
    {
        return ['1' => __('Diffdata 1'), '2' => __('Diffdata 2'), '3' => __('Diffdata 3'), '4' => __('Diffdata 4'), '5' => __('Diffdata 5')];
    }


    public function getTypedataTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['typedata']) ? $data['typedata'] : '');
        $list = $this->getTypedataList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getDiffdataTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['diffdata']) ? $data['diffdata'] : '');
        $list = $this->getDiffdataList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusList()
    {
        return ['1' => __('Status 1'), '2' => __('Status 2'), '3' => __('Status 3')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }



    public function course()
    {
        return $this->belongsTo('Course', 'course_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function setOptionjsonAttr($value)
    {
        // 数组
      $value = json_decode($value,true);
      $v = array_column($value,'value');
      return json_encode($v);
    }

    // 设置答案
    public function setAnswersAttr($value,$data)
    {
        if($data["typedata"] == 4){
            $v = $value[0];
            $value = explode(PHP_EOL,$v);
        }
        return json_encode($value,JSON_UNESCAPED_UNICODE);
    }
    // 获取答案
    public function getAnswersAttr($value,$data)
    {
        if($data["typedata"] == 4){
            $arr = json_decode($value,true);
            $value = implode(PHP_EOL,$arr);
            $value = json_encode([ $value ]);
        }
        return $value;
    }

    public function getOptionjsonAttr($value)
    {
        // 数组
      $value = json_decode($value,true);
      $newVal = [];
      foreach ($value as $k => $v) {
        $newVal[]["value"] = $v;
      }
      return json_encode($newVal);
    }
}
